package zm.irc.weechat;


import org.apache.log4j.Logger;


import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import zm.irc.cfg.WeechatConfig;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.message.receive.IrcReceiveMessage;
import zm.irc.util.HttpUtil;
import zm.irc.util.JsonUtils;
import zm.irc.weechat.pojo.WeechatMessage;

@Service(isSinglet = true)
public class WeechatClient {
    private static final Logger log = Logger.getLogger(WeechatClient.class);
    private static final String URL_SEND = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s";
    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final Integer ACCESS_TOKEN_EXPIRED = 42001;

    @AutoWired
    private WeechatTokenUtil tokenUtil;

    @AutoWired
    private WeechatConfig weechatConfig;


    private String token;
 

    public WeechatClient(){

    }


   
    public void send(IrcReceiveMessage receivedMsg){
        String token = this.getToken(false);
        if(StringUtils.isNullOrEmpty(token)){
            return;
        }

        Integer errorCode = this.doSend(receivedMsg.getMessageForPrint(),  token);
        if( ACCESS_TOKEN_EXPIRED.equals(errorCode) ){
            token = this.getToken(true);
            this.doSend("【重新获取token】",  token);//retry
            this.doSend(receivedMsg.getMessageForPrint(),  token);//retry
        }
       

    }

    private Integer doSend(String msg, String token){
        LocalDateTime now = LocalDateTime.now();
        String nowStr = df.format(now);

        String url = String.format(URL_SEND, token);
    
        WeechatMessage weechatMsg = WeechatMessage.build()
                                .toAllUser()
                                .textType()
                                .agentId(this.weechatConfig.getAgentid())
                                .content(nowStr + " : " + msg);
                               
                               
        String resultJson = HttpUtil.postJson(url, weechatMsg.toString(), null);
        JSONObject result = JsonUtils.jsonToBean(resultJson, JSONObject.class);
        Integer errorCode = result.getInteger("errcode");
      

        boolean isSucceed = errorCode == 0;
        if( !isSucceed){
            log.error(resultJson);
        }
        return errorCode;
    }

    private String getToken(boolean forceRefresh){
        if( forceRefresh || StringUtils.isNullOrEmpty(this.token) ){
            this.token = this.tokenUtil.getToken(this.weechatConfig.getCorpid(), this.weechatConfig.getCorpsecret());
        }
       
        return this.token;
    }

}